// 获取上一周的所有周任务中置顶的项
const schedule = require("node-schedule");

const { getList, getResult } = require("../utils/sql");

function getWeekRange(date) {
  // 获取当前日期是星期几（0 是周日，1 是周一，...，6 是周六）
  const dayOfWeek = date.getDay();
  // 计算本周的周一
  const startOfWeek = new Date(date);
  startOfWeek.setDate(date.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1));
  // 计算本周的周日
  const endOfWeek = new Date(startOfWeek);
  endOfWeek.setDate(startOfWeek.getDate() + 6);
  // 格式化日期为 'YYYY-MM-DD'
  const formatDate = (d) => d.toISOString().split("T")[0];
  return `${formatDate(startOfWeek)} ~ ${formatDate(endOfWeek)}`;
}

function getLastAndThisWeek() {
  const today = new Date();
  const lastWeek = new Date(today);
  lastWeek.setDate(today.getDate() - 7); // 获取上周的日期

  const currentWeekRange = getWeekRange(today);
  const lastWeekRange = getWeekRange(lastWeek);

  return {
    currentWeek: currentWeekRange,
    lastWeek: lastWeekRange,
  };
}

async function getUserInfo() {
  let result = await getList("user");
  let userList = result.filter((item) => item.email);
  userList.forEach((user) => getLastWeekPlan(user));
}

async function getLastWeekPlan(user) {
  let { currentWeek, lastWeek } = getLastAndThisWeek();

  let result = await getList(
    "weekly_task",
    ["date", "user_id", "top"],
    [lastWeek, user.user_id, 1]
  );
  if (result.length === 0) return;

  let addPromises = result.map((item) => {
    return new Promise(async (resolve) => {
      let sql = `INSERT INTO weekly_task (task,date,user_id,top,date) value(?,?,?,?)`;
      let paramsList = [item.task, currentWeek, user.user_id, 1];
      await getResult({ sql, paramsList });
      resolve();
    });
  });

  Promise.all(addPromises).then((res) => {
    console.log(res);
  });
}

schedule.scheduleJob("5 0 0 * * 1", () => {
  getUserInfo();
});
